import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './index.css';
import { getApiUrl } from '../../config/api';

export const FeedbackPage = () => {
  const navigate = useNavigate();
  const [feedback, setFeedback] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const handleBack = () => {
    navigate('/settings');
  };

  const handleSubmit = async () => {
    if (!feedback.trim()) {
      alert('请输入反馈内容');
      return;
    }

    setSubmitting(true);
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        alert('请先登录');
        navigate('/login');
        return;
      }

      const cleanToken = token.replace(/['"]+/g, '');
      const response = await fetch(getApiUrl('/api/feedback/submit'), {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${cleanToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ content: feedback })
      });

      if (response.status === 401) {
        // token 过期，跳转到登录页
        alert('登录已过期，请重新登录');
        localStorage.removeItem('token'); // 清除过期的 token
        navigate('/login');
        return;
      }

      const data = await response.json();
      if (data.ok) {
        alert('感谢您的反馈！');
        navigate('/settings');
      } else {
        throw new Error(data.error || '提交失败');
      }
    } catch (error) {
      console.error("提交反馈失败:", error);
      alert('提交失败，请稍后重试');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="feedback-page">
      <div className="feedback-header">
        <div className="back-button" onClick={handleBack}>
          <span className="back-arrow">‹</span>
          <span>返回</span>
        </div>
        <h1>帮助与反馈</h1>
      </div>

      <div className="feedback-content">
        <div className="feedback-section">
          <h2>常见问题</h2>
          <div className="faq-item">
            <h3>1. AI Cube 是什么？</h3>
            <p>AI Cube 是一个智能对话助手，可以帮助你解答问题、编写代码等。</p>
          </div>
          <div className="faq-item">
            <h3>2. 如何开始对话？</h3>
            <p>在对话框中输入你的问题，点击发送按钮即可开始对话。</p>
          </div>
        </div>

        <div className="feedback-section">
          <h2>意见反馈</h2>
          <textarea
            placeholder="请输入您的意见或建议..."
            value={feedback}
            onChange={(e) => setFeedback(e.target.value)}
            disabled={submitting}
          />
          <button 
            className="submit-button" 
            onClick={handleSubmit}
            disabled={submitting}
          >
            {submitting ? '提交中...' : '提交反馈'}
          </button>
        </div>
      </div>
    </div>
  );
};